package com.exam.demo.job;

import com.exam.demo.mapreduce.FixTemperatureMapper;
import com.exam.demo.mapreduce.FixTemperatureReducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 * @author SongYueSheng
 * @date 2024/6/7 14:08
 */
public class HadoopJobRunner implements Tool {
    private Configuration conf;

    @Override
    public void setConf(Configuration conf) {
        this.conf = conf;
    }

    @Override
    public Configuration getConf() {
        return this.conf;
    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        Job job = Job.getInstance(conf, "Temperature Range Count");
        job.setJarByClass(HadoopJobRunner.class);

        job.setMapperClass(FixTemperatureMapper.class);
        job.setReducerClass(FixTemperatureReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        return job.waitForCompletion(true) ? 0 : 1;
    }

    public void runJob(String inputPath, String outputPath, Configuration conf) throws Exception {
        setConf(conf);
        String[] args = {inputPath, outputPath};
        ToolRunner.run(conf, new HadoopJobRunner(), args);
    }
}
